package com.jackrain.nea.omslocal.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import com.aliyun.openservices.ons.api.impl.util.MsgConvertUtil;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;

/**
 * @Discription: 保存发送失败消息体
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2017/12/28 19:09
 */
@Slf4j
@Component
public class SaveAllMsgService {

    @Autowired
    private ProducerBean producerBean;
    @Autowired
    private PropertiesConf pconf;

    public void saveFailedMsg(JSONObject object, String topic, String tag) {

        try {
            String insertSql = "insert into t_failedmsg (id,msgbody,) values ()";
            QueryEngine.getInstance().executeUpdate(insertSql, new Object[]{});

        } catch (Exception e) {
            // 插入消息异常
            log.debug("保存消息信息失败 topic :" + topic + e.getMessage().toString());
        }

    }


    /**
     * 库存消息再次延时发送
     * @param dataobject
     * @param topic
     * @param ctag
     * @throws Exception
     */
    public void sendMqinfoObj(JSONObject dataobject, String topic, String ctag) {
        Message msg = null;
        String str = UUID.randomUUID().toString();

        try {
            msg = new Message(topic, ctag, MsgConvertUtil
                    .objectSerialize(dataobject));
            msg.setKey(str);
            SendResult sendResult = producerBean.send(msg);
            assert sendResult != null;

            log.debug("send success: MSGKEY[" + str + "] ---" + topic + "========" + ctag);

        } catch (ONSClientException e) {
            // 消息发送失败,保存到 临时表,以任务发送
            if (pconf.getProperty("lons.accessKey") == topic) {

                log.debug("同步库存数据发送失败");
                return;
            }

        } catch (IOException i) {
            // 序列化,流错误
            log.debug("序列化错误,消息发送失败");
        }

    }

}
